<script setup>
import { ref, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import axios from '@/utils/axios.js';
import { ElTable, ElTableColumn, ElCard } from 'element-plus';

const route = useRoute();
const product = ref(null);

const fetchProductDetail = async (productId) => {
  try {
    const response = await axios.get(`http://localhost:5173/api/products/${productId}`);
    product.value = response.data;
  } catch (error) {
    console.error('获取商品详情失败:', error);
  }
};

onMounted(() => {
  const productId = parseInt(route.query.id);
  if (!isNaN(productId)) {
    fetchProductDetail(productId);
  }
});

watch(
  () => route.query.id, // 监听的数据源
  (newId, oldId) => {
    if (newId !== oldId) { // 仅在ID变化时执行
      const productId = parseInt(newId);
      if (!isNaN(productId)) {
        fetchProductDetail(productId);
      }
    }
  },
  { immediate: true } // 初始渲染时立即执行一次
);
</script>

<template>
  <el-card class="product-card">
    <div v-if="product">
<!--      通过 [product] 将单个对象转换为 包含一个元素的数组，使表格能正确渲染-->
      <el-table :data="[product]" border style="width: 100%">
        <el-table-column prop="id" label="商品ID" width="120" />
        <el-table-column prop="name" label="商品名称" />
        <el-table-column prop="info" label="商品信息" />
      </el-table>
    </div>
    <div v-else>
      <p>加载中或商品不存在...请检查后端是否运行</p>
    </div>
  </el-card>
</template>

<style scoped>
.product-card {
  max-width: 800px;
  margin: 20px auto;
}
</style>